﻿
//ham lay gia tri cua tham so tren url
function getPramJs(param) {
    var query = window.location.search.substring(1);
    var parms = query.split('&');
    for (var i = 0; i < parms.length; i++) {
        var pos = parms[i].indexOf('=');
        if (pos > 0) {
            var key = parms[i].substring(0, pos).toLowerCase();
            var val = parms[i].substring(pos + 1);
            if (key == param.toLowerCase())
                return val;
        }
    }
    return null;
}
//ham lay dia chi url hien tai
function getUrlLocal() {
    var requestURL = window.document.location.toString();
    var end = requestURL.lastIndexOf("/") + 1;
    requestURL = requestURL.substring(0, end);

    return requestURL;
}

/*begin cac ham lien quan den chuoi*/
function Trim(iStr) {
    while (iStr.charCodeAt(0) <= 32) {
        iStr = iStr.substr(1);
    }

    while (iStr.charCodeAt(iStr.length - 1) <= 32) {
        iStr = iStr.substr(0, iStr.length - 1);
    }

    return iStr;
}
function Left(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0, n);
}

function Right(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
}
function CharReplace(iStr) {
    var r1 = /%26/g;
    var r2 = /%20/g;
    var r3 = /%22/g;
    iStr = iStr.replace(r1, '&');
    iStr = iStr.replace(r2, ' ');
    iStr = iStr.replace(r3, '"');
    return iStr;
}
//Check if string is non-blank
function isNonblank(txt) {
    var isNonblank_re = /\S/;
    return String(s).search(isNonblank_re) != -1
}
//cho phep nhung ky tu tu A->Z, a->z, 0->9,va cac ky tu _-
function CheckChar(stringIn) {

    retval = false
    var i;
    for (i = 0; i <= stringIn.length - 1; i++) {
        if (((stringIn.charCodeAt(i) >= 48) && (stringIn.charCodeAt(i) <= 57)) || ((stringIn.charCodeAt(i) > 64) && (stringIn.charCodeAt(i) <= 90)) || ((stringIn.charCodeAt(i) >= 97) && (stringIn.charCodeAt(i) <= 122)) || (stringIn.charCodeAt(i) == 95) || (stringIn.charCodeAt(i) == 45)) {
            retval = true;
        }
        else {
            retval = false;
            break;
        }
    }
    return retval;
}
//kiem tra cac ky tu dat biet @,<,>,!,$,%,(,),=,#,{,},[,],',".
function Checkspecialword(stringIn) {

    if ((stringIn.indexOf("@") >= 0) || (stringIn.indexOf("<") >= 0) || (stringIn.indexOf(">") >= 0) || (stringIn.indexOf("!") >= 0) || (stringIn.indexOf("$") >= 0) || (stringIn.indexOf("%") >= 0) || (stringIn.indexOf("(") >= 0) || (stringIn.indexOf(")") >= 0) || (stringIn.indexOf("=") >= 0) || (stringIn.indexOf("#") >= 0) || (stringIn.indexOf("{") >= 0) || (stringIn.indexOf("}") >= 0) || (stringIn.indexOf("[") >= 0) || (stringIn.indexOf("]") >= 0) || (stringIn.indexOf("'") >= 0) || (stringIn.indexOf('"') >= 0)) {
        return false;
    }
    return true;
}

//khong cho phep cac so 0-9
function CheckChar2(stringIn) {
    var i;
    for (i = 0; i <= stringIn.length - 1; i++) {
        if ((stringIn.charCodeAt(i) >= 48) && (stringIn.charCodeAt(i) <= 57)) {
            return false;
        }
    }
    return true;
}

function Checkspecialword1(stringIn) {

    retval = false
    var i;
    for (i = 0; i <= stringIn.length - 1; i++) {
        if (((stringIn.charCodeAt(i) >= 8) && (stringIn.charCodeAt(i) <= 127)) && (stringIn.charCodeAt(i) != 34) && (stringIn.charCodeAt(i) != 39) && (stringIn.charCodeAt(i) != 32)) {
            retval = true;
        }
        else {
            retval = false;
            break;
        }
    }
    return retval;
}

//kiem tra cac ky tu dat biet @,<,>,!,$,%,(,),=,#,{,},[,],",^,~,`,,/,\,|,*,.,+,:
function CheckChar(stringIn) {

    if ((stringIn.indexOf("@") >= 0) || (stringIn.indexOf("<") >= 0) || (stringIn.indexOf(">") >= 0) || (stringIn.indexOf("!") >= 0) || (stringIn.indexOf("$") >= 0) || (stringIn.indexOf("%") >= 0) || (stringIn.indexOf("(") >= 0) || (stringIn.indexOf(")") >= 0) || (stringIn.indexOf("=") >= 0) || (stringIn.indexOf("#") >= 0) || (stringIn.indexOf("{") >= 0) || (stringIn.indexOf("}") >= 0) || (stringIn.indexOf("[") >= 0) || (stringIn.indexOf("]") >= 0) || (stringIn.indexOf("|") >= 0) || (stringIn.indexOf('"') >= 0) || (stringIn.indexOf(".") >= 0) || (stringIn.indexOf("?") >= 0) || (stringIn.indexOf(",") >= 0) || (stringIn.indexOf("+") >= 0) || (stringIn.indexOf("&") >= 0) || (stringIn.indexOf(":") >= 0) || (stringIn.indexOf("\\") >= 0) || (stringIn.indexOf("/") >= 0) || (stringIn.indexOf("*") >= 0) || (stringIn.indexOf("`") >= 0) || (stringIn.indexOf("~") >= 0) || (stringIn.indexOf("^") >= 0) || (stringIn.indexOf("-") >= 0) || (stringIn.indexOf("_") >= 0)) {
        return false;
    }
    return true;
}

function ClearSpecialWord(id) {
    id.value = filterNum(id.value)
    function filterNum(str) {
        re = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|\./g;
        // remove special characters like "$" and "," etc...
        return str.replace(re, "");
    }
}
/*end cac ham lien quan den chuoi*/

///46:.
///44:,
///47:/
function onkeypressnumber(myfiled, e, valregex) {
    var regex = /[0-9]|\./;
    //var regex = /[0-9]|\,/;
    //var regex = /[0-9]|\x/;
    if (valregex == "") {
        regex = /[0-9]/;
    }
    else if (valregex == ".") {
        regex = /[0-9]|\./;
    }
    else if (valregex == "-") {
        regex = /[0-9]|\-/;
    }
    else if (valregex == "x") {
        regex = /[0-9]|x/;
    }
    
    var key, keychar;
    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);
    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
        return true;
    // numbers
    else if (regex.test(keychar)) {
        //numberFormat(myfiled.id, myfiled.value);
        return true; 
    }
    else
        return false;
}

//	Kiem tra email nhap vao co hop le khong
function KiemTraEmail(txtEmail) {
    var email = txtEmail.value;
    if (email == null || email == "") {
        return false;
    }
    if (CheckEmail(email) == false) {        
        return false;
    }

    return true;
}
/*Check email*/
function CheckEmail(stringIn) {
    var re = /^([A-Za-z0-9\_\-]+\.)*[A-Za-z0-9\_\-]+@[A-Za-z0-9\_\-]+(\.[A-Za-z0-9\_\-]+)+$/;
    if (stringIn.search(re) == -1) {
        return false;
    }
    else {
        return true;
    }
}

function CheckEmailAddress(Email) {
    Email = Trim(Email);
    while (Email != '') {
        c = Email.charAt(0);
        if (c == ' ' || c == '<' || c == 39 || c == ':' || c == '.') {
            Email = Email.substr(1);
        }
        else {
            break;
        }
    }
    i = Email.indexOf('>');
    if (i == -1) {
        while (Email != '') {
            c = Email.charAt(Email.length - 1);
            if (c == ' ' || c == 39 || c == '.') {
                Email = Email.substr(0, Email.length - 1);
            }
            else {
                break;
            }
        }
    }
    else {
        Email = Email.substr(0, i);
    }
    if (Email.length > 96)
        return '';
    i = Email.lastIndexOf('@');
    j = Email.lastIndexOf('.');
    if (i < j)
        i = j;
    switch (Email.length - i - 1) {
        case 2:
            break;
        case 3:
            switch (Email.substr(i)) {
                case '.com':
                case '.net':
                case '.org':
                case '.edu':
                case '.mil':
                case '.gov':
                case '.biz':
                case '.pro':
                case '.int':
                    break;
                default:
                    return '';
            }
            break;
        default:
            switch (Email.substr(i)) {
                case '.name':
                case '.info':
                    break;
                default:
                    return '';
            }
            break;
    }
    Email = Email.toLowerCase();
    if (Email == '')
        return '';
    if (Email.indexOf(' ') != -1)
        return '';
    if (Email.indexOf('..') != -1)
        return '';
    if (Email.indexOf('.@') != -1)
        return '';
    if (Email.indexOf('@.') != -1)
        return '';
    if (Email.indexOf(':') != -1)
        return '';
    for (i = 0; i < Email.length; i++) {
        c = Email.charAt(i);
        if (c >= '0' && c <= '9')
            continue;
        if (c >= 'a' && c <= 'z')
            continue;
        if ('`~!#$%^&*-_+=?/\\|@.'.indexOf(c) != -1)
            continue;
        return '';
    }
    if ((i = Email.indexOf('@')) == -1)
        return '';
    if (Email.substr(i + 1).indexOf('@') != -1)
        return '';
    if (Email.charAt(0) == '.' || Email.charAt(Email.length - 1) == '.')
        return '';
    return Email;
}

// Check if string is a whole number(digits only).
function isWhole(s) {
    var isWhole_re = /^\s*\d+\s*$/;
    return String(s).search(isWhole_re) != -1
}

//// checks that an input string is an integer, with an optional +/- sign character.
function isInteger(s) {
    var isInteger_re = /^\s*(\+|-)?\d+\s*$/;
    return String(s).search(isInteger_re) != -1
}

// Checks that an input string is a decimal number, with an optional +/- sign character.
function isDecimal(s) {
    var isDecimal_re = /^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/;
    return String(s).search(isDecimal_re) != -1
}
// Check if string is currency
function isCurrency(s) {
    var isCurrency_re = /^\s*(\+|-)?((\d+(\.\d\d)?)|(\.\d\d))\s*$/;
    return String(s).search(isCurrency_re) != -1
}
// This function removes non-numeric characters
function stripNonNumeric(str) {
    str += '';
    var rgx = /^\d|\.|-$/;
    var out = '';
    for (var i = 0; i < str.length; i++) {
        if (rgx.test(str.charAt(i))) {
            if (!((str.charAt(i) == '.' && out.indexOf('.') != -1) ||
             (str.charAt(i) == '-' && out.length != 0))) {
                out += str.charAt(i);
            }
        }
    }
    return out;
}
//kiem tra so 
function CheckNumber(stringIn) {
    retval = false
    var i;
    for (i = 0; i <= stringIn.length - 1; i++) {
        if ((stringIn.charCodeAt(i) >= 48) && (stringIn.charCodeAt(i) <= 57)) {
            retval = true;
        }
        else {
            retval = false;
            break;
        }
    }
    return retval;
}

// Check for valid credit card type/number
function isValidCC(cctype, ccnumber) {
    var creditCardList = [
    //type      prefix   length
     ["amex", "34", 15],
     ["amex", "37", 15],
     ["disc", "6011", 16],
     ["mc", "51", 16],
     ["mc", "52", 16],
     ["mc", "53", 16],
     ["mc", "54", 16],
     ["mc", "55", 16],
     ["visa", "4", 13],
     ["visa", "4", 16]];

    var cc = getdigits(ccnumber);
    if (luhn(cc)) {
        for (var i in creditCardList) {
            if (creditCardList[i][0] == (cctype.toLowerCase())) {
                if (cc.indexOf(creditCardList[i][1]) == 0) {
                    if (creditCardList[i][2] == cc.length) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

/*number Format*/
function numberFormat(num, decimalNum, bolLeadingZero, bolParens, bolCommas) {
    if (isNaN(parseInt(num))) return "0";

    var tmpNum = num;
    var iSign = num < 0 ? -1 : 1;

    tmpNum *= Math.pow(10, decimalNum);
    tmpNum = Math.round(Math.abs(tmpNum))
    tmpNum /= Math.pow(10, decimalNum);
    tmpNum *= iSign;

    var tmpNumStr = new String(tmpNum);

    if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
        if (num > 0)
        tmpNumStr = tmpNumStr.substring(1, tmpNumStr.length);
    else
        tmpNumStr = "-" + tmpNumStr.substring(2, tmpNumStr.length);

    if (bolCommas && (num >= 1000 || num <= -1000)) {
        var iStart = tmpNumStr.indexOf(".");
        if (iStart < 0)
            iStart = tmpNumStr.length;

        iStart -= 3;
        while (iStart >= 1) {
            tmpNumStr = tmpNumStr.substring(0, iStart) + "," + tmpNumStr.substring(iStart, tmpNumStr.length)
            iStart -= 3;
        }
    }
    if (bolParens && num < 0)
        tmpNumStr = "(" + tmpNumStr.substring(1, tmpNumStr.length) + ")";
    return tmpNumStr;
}

/*format number in textbox*/
/*thanh.lu - 09/11/2009*/
function RemoveFormat(str) {
    var strReturn = str;
    while (strReturn.indexOf(',') != -1) {
        strReturn = strReturn.replace(',', '');
    }
    return strReturn;
}
function numberFormat(nStr, idtxt) {

    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    var temp = RemoveFormat(x1);
    x1 = temp;
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    document.getElementById(idtxt).value = x1 + x2;
}

/*Format date*/
function dFormat(strDate) {
    var rStr = '';
    if (strDate == '') {
        sDate = rStr;
    }
    else {
        var tDates = strDate.split(" ");
        var tDay = tDates[0].split("/");
        var tTime = tDates[1].split(":");
        var oDay = new Date();
        oDay.setFullYear(tDay[2], tDay[0] - 1, tDay[1]);
        switch (oDay.getDay()) {
            case 0:
                rStr = 'Ch&#7911; nh&#7853;t'; break;
            case 1:
                rStr = 'Th&#7913; hai'; break;
            case 2:
                rStr = 'Th&#7913; ba'; break;
            case 3:
                rStr = 'Th&#7913; t&#432;'; break;
            case 4:
                rStr = 'Th&#7913; n&#259;m'; break;
            case 5:
                rStr = 'Th&#7913; s&#225;u'; break;
            case 6:
                rStr = 'Th&#7913; b&#7843;y'; break;
            default:
                rStr = ''; break;
        }
        rStr = rStr.concat(', ').concat(tDay[1]).concat('/').concat(tDay[0]).concat('/').concat(tDay[2]).concat(' | ');
        if (tDates[2] == 'AM') {
            if (tTime[0] < 10) {
                rStr = rStr.concat('0').concat(tTime[0]).concat(':');
            }
            else {
                rStr = rStr.concat(tTime[0]).concat(':');
            }
        }
        else {
            tTime[0] = 12 + parseInt(tTime[0]);
            rStr = rStr.concat(tTime[0]).concat(':');
        }

        if (tTime[1] < 10) {
            rStr = rStr.concat('0').concat(tTime[1]);
        }
        else {
            rStr = rStr.concat(tTime[1]);
        }

        rStr = rStr.concat(' GMT+7&nbsp;');
        sDate = rStr;
    }
}
function dmy(strDate) {
    var temp = new Array();
    temp = strDate.split('/');
    return temp[1].concat('/').concat(temp[0]).concat('/').concat(temp[2]);
}


///*check size*/
//function checkFileSize() {
//    if (navigator.userAgent.indexOf("Firefox") != -1) {
//        checkFileSizeFireFox();
//    } else {
//        checkFileSizeIE();
//    }
//}

//// It is working well with FireFox
//function checkFileSizeFireFox() {
//    var node = document.getElementById('file');
//    alert('fileSize = ' + node.files[0].fileSize);
//}

//// It is working well with IE
//function checkFileSizeIE() {
//    var myFSO = new ActiveXObject("Scripting.FileSystemObject");
//    var filepath = document.upload.file.value;
//    var thefile = myFSO.getFile(filepath);
//    var size = thefile.size;
//    alert(size + " bytes");
//}

function onkeypressnumber(e, dec) {
    var regex = /[0-9]|\./;    
    var key, keychar;
    if (window.event) { key = window.event.keyCode ? window.event.keyCode : e.which; }
    else { key = e.which; }
    if (!dec) regex = /[0-9]/;
    keychar = String.fromCharCode(key);
    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
        return true;
    else if (regex.test(keychar)) {        
        return true;
    }
    else {
        return false;
    }
}
// Created: son.nguyen
// Date:    26/03/2010
function extractValidationNumbers(obj, decimalPlaces, allowNegative) {
    var temp = obj.value;
    // avoid changing things if already formatted correctly
    var reg0Str = '[0-9]*';
    if (decimalPlaces > 0) {
        reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
    } else if (decimalPlaces < 0) {
        reg0Str += '\\.?[0-9]*';
    }
    reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
    reg0Str = reg0Str + '$';
    var reg0 = new RegExp(reg0Str);
    if (reg0.test(temp)) {
        if (allowNegative && temp.length > 0 && temp.charAt(0) == '-') {
            temp = addCommas(temp.substring(1), '-');
        }
        else {
            temp = addCommas(temp, '');
        }
        obj.value = temp;
        return true;
    }
    // first replace all non numbers
    var reg1Str = '[^0-9' + (decimalPlaces != 0 ? ',' : '') + (allowNegative ? '-' : '') + ']';
    var reg1 = new RegExp(reg1Str, 'g');
    temp = temp.replace(reg1, '');
    if (allowNegative) {
        // replace extract negative
        var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
        var reg2 = /-/g;
        temp = temp.replace(reg2, '');
        if (hasNegative) temp = '-' + temp;
    }
    if (decimalPlaces != 0) {
        var reg3 = /\./g;
        var reg3Array = reg3.exec(temp);
        if (reg3Array != null) {
            // keep only first occurrence of . 
            //  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
            var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
            reg3Right = reg3Right.replace(reg3, '');
            reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
            temp = temp.substring(0, reg3Array.index) + ',' + reg3Right;
        }
    }
    //format number
    if (allowNegative && temp.length > 0 && temp.charAt(0) == '-') {
        temp = addCommas(temp.substring(1), '-');
    }
    else {
        temp = addCommas(temp, '');
    }   
    obj.value = temp;
}
// Created: son.nguyen
// Date:    26/03/2010
function inputValidationNumbers(obj, e, allowDecimal, allowNegative) {
    var key;
    var isCtrl = false;
    var keychar;
    var reg;
    if (window.event) {
        key = e.keyCode;
        isCtrl = window.event.ctrlKey
        if (e.keyCode == 0 && window.event.which == 1) {
            key = e.which;
            isCtrl = e.ctrlKey;
        }
    }
    else if (e.which) {
        key = e.which;
        isCtrl = e.ctrlKey;
    }
    if (isNaN(key)) return true;
    keychar = String.fromCharCode(key);
    // check for backspace or delete, or if Ctrl was pressed
    if (key == 8 || isCtrl) {
        return true;
    }
    reg = /\d/;
    var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
    var isFirstD = allowDecimal ? keychar == ',' && obj.value.indexOf(',') == -1 : false;

    return isFirstN || isFirstD || reg.test(keychar);
}
// Created: son.nguyen
// Date:    26/03/2010
function addCommas(nStr, prefix) {
    var prefix = prefix || '';
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? ',' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1))
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    return prefix + x1 + x2;
}